/* eslint-disable */
import elementHelper from 'bpmn-js-properties-panel/lib/helper/ElementHelper'
import cmdHelper from 'bpmn-js-properties-panel/lib/helper/CmdHelper'
import entryFactory from '../EntryFactory';

import { is } from 'bpmn-js/lib/util/ModelUtil'
import { find, forEach } from 'lodash'

/**
 * Get all camunda:property objects for a specific business object
 *
 * @param  {ModdleElement} parent
 *
 * @return {Array<ModdleElement>} a list of camunda:property objects
 */
function getPropertyValues(parent) {
  let properties = parent && getPropertiesElement(parent);
  if (properties && properties.values) {
    return properties.values;
  }
  return [];
}

/**
 * Get all camunda:Properties object for a specific business object
 *
 * @param  {ModdleElement} parent
 *
 * @return {ModdleElement} a camunda:Properties object
 */
function getPropertiesElement(element) {
  if (!isExtensionElements(element)) {
    return element.properties;
  } else {
    return getPropertiesElementInsideExtensionElements(element);
  }
}
/**
 * Get first camunda:Properties object for a specific bpmn:ExtensionElements
 * business object.
 *
 * @param {ModdleElement} extensionElements
 *
 * @return {ModdleElement} a camunda:Properties object
 */
function getPropertiesElementInsideExtensionElements(extensionElements) {
  return find(extensionElements.values, function (elem) {
    return is(elem, 'camunda:Properties');
  });
}

/**
 * Returns true, if the given business object is a bpmn:ExtensionElements.
 *
 * @param {ModdleElement} element
 *
 * @return {boolean} a boolean value
 */
function isExtensionElements(element) {
  return is(element, 'bpmn:ExtensionElements');
}

/**
 * get的钩子函数
 * @param {element} element
 * @param {String} currentName 目标的名称
 * @param {String} key键值 modelProperty
 * @return {Object} 返回value
 */
function getHandle(element, currentName, key) {
  let bo = element.businessObject,
      valueList = getPropertyValues(bo.extensionElements),
      currnetValue = { value: '' }

      forEach(valueList, function(property) {
        if (property.name === currentName) {
          currnetValue = property
        }
      })
    if (!currnetValue.value) {
      currnetValue.value = false
    }
  return { [key]: currnetValue.value }
}

export default function AdvancePermissions(group, element, bpmnFactory, translate) {

  if (is(element, 'bpmn:UserTask')) {
    const addElement = function (setValue, currentName) {
      // 如果没有ExtensionElements节点，表示没有添加过额外属性
      // 创建一个新的节点，并初始化内容
      if (!element.businessObject.extensionElements) {
        let command = []
        let parent = elementHelper.createElement('bpmn:ExtensionElements', {
          values: []
        }, element.businessObject, bpmnFactory) // 创建bpmn:ExtensionElements节点
        let cmd = cmdHelper.updateBusinessObject(element, element.businessObject, {
          extensionElements: parent
        }); // 更新element.bo节点
        command.push(cmd)

        // 创建camunda:Properties节点
        const properties = elementHelper.createElement('camunda:Properties', {}, parent, bpmnFactory)

        // 添加ExtensionElements节点
        command.push(cmdHelper.addAndRemoveElementsFromList(
          element,
          parent,
          'values',
          'extensionElements',
          [properties],
          []
        ))
        
        // 确定property节点的属性
        let propertyProps = {}
        propertyProps.name = currentName
        propertyProps.value = setValue.value
        
        // 创建property节点
        let property = elementHelper.createElement('camunda:Property', propertyProps, properties, bpmnFactory)
        // 将property节点添加进入刚才创建的properties中
        command.push(cmdHelper.addElementsTolist(element, properties, 'values', [property]));
        
        console.log(command)
        return command
      // 如果有节点，就根据节点类型添加或修改节点
      } else {
        let parent = element.businessObject.extensionElements, // 确定父节点位置
            inx    = -1 // 初始化property节点索引
        const propertys = getPropertyValues(parent) // 查找到所有的property节点集合

        forEach(propertys, function(property, index) {
          // 根据当前目标属性的名称查找到正确的property节点索引
          if (property.name === currentName) {
            inx = index
          }
        })

        if (inx === -1) {
          inx = 0
        }
        // 赋值正确的property节点
        let property = propertys[inx]
        
        // 如果有当前的属性节点
        if (property.name === currentName) {
          // 更新目标节点值
          return cmdHelper.updateBusinessObject(element, property, setValue)
        } else {
          // 如果没有当前的属性节点
          let commandC = []
          let properties = getPropertiesElement(parent) // 返回properties节点
          // 更新properites节点
          // commandC.push(cmdHelper.updateBusinessObject(element, parent, { 'properties': properties }))

          let propertyProps = {}
          propertyProps.name = currentName
          propertyProps.value = setValue.value
          // 创建新的Property节点
          let property = elementHelper.createElement('camunda:Property', propertyProps, properties, bpmnFactory);
          // 添加新的property节点
          commandC.push(cmdHelper.addElementsTolist(element, properties, 'values', [ property ]));

          return commandC
        }
      }
    }

    /**
     * 判断有没有当前要设置的属性节点
     */
    function isProperty(element, currentName) {
      let parent = element.businessObject.extensionElements,
            inx    = -1
        const propertys = getPropertyValues(parent)

        forEach(propertys, function(property, index) {
          if (property.name === currentName) {
            inx = index
          }
        })

        return inx > -1
    }

    const checkboxs = [
      {
        id: 'approvalOpinion',
        label: '审批意见',
        modelProperty: 'approvalOpinion',
        description: '（如勾选，审批人必须填写审批意见才可提交审批结果）',
        get: function (element) {
          // 如果是第一次加载，并且没有extensionElements元素，则初始化数据
          if (this.firstLoda && !element.businessObject.extensionElements) {
            this.firstLoda = false
            // 点击按钮触发set事件
            document.getElementById('camunda-approvalOpinion').click()
          } else if (!isProperty(element, 'isCommentRequired')) {
            document.getElementById('camunda-approvalOpinion').click()
          }
          return getHandle(element, 'isCommentRequired', 'approvalOpinion')
        },
        set: function (element, values) {
          console.log(values)
          return addElement({
            value: values.approvalOpinion,
          }, 'isCommentRequired')
        }
      },
      {
        id: 'TheSponsorNotVisible',
        label: '对发起人可见',
        modelProperty: 'TheSponsorNotVisible',
        description: '（如勾选，则审批意见对申请人可见）',
        get: function (element) {
          // 同审批意见
          if (this.firstLoda && !element.businessObject.extensionElements) {
            this.firstLoda = false
            document.getElementById('camunda-TheSponsorNotVisible').click()
          } else if (!isProperty(element, 'isInitiatorShow')) {
            document.getElementById('camunda-TheSponsorNotVisible').click()
          }
          return getHandle(element, 'isInitiatorShow', 'TheSponsorNotVisible')
        },
        set: function (element, values) {
          console.log(values)
          return addElement({
            value: values.TheSponsorNotVisible
          }, 'isInitiatorShow')
        }
      }
    ]

    forEach(checkboxs, function(checkbox) {
      group.entries.push(entryFactory.checkbox(checkbox))
    })

  }
}